import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Upload,
  Image,
  Space,
  Popconfirm,
  message,
  Tag,
  Card,
  DatePicker,
  Progress,
} from "antd";
import dayjs from "dayjs";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  VerticalAlignTopOutlined,
  VerticalAlignBottomOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import type { UploadProps } from "antd/es/upload";
import { AdminControllerService, Service } from "../api";
import type { VidVideo_, VideoListParam } from "../api";
import { getToken } from "../utils/auth";

interface VideoData {
  id?: string;
  title?: string;
  coverId?: string;
  fileId?: string;
  compilationId?: string;
  sortNum?: string;
  freeState?: boolean;
  createdTime?: string;
  updatedTime?: string;
}

interface CompilationData {
  id?: string;
  name?: string;
  sortNum?: string;
}

const VideoManagement: React.FC = () => {
  const [videos, setVideos] = useState<VideoData[]>([]);
  const [compilations, setCompilations] = useState<CompilationData[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingVideo, setEditingVideo] = useState<VideoData | null>(null);
  const [loading, setLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [coverUploading, setCoverUploading] = useState(false);
  const [videoUploading, setVideoUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [searchParams, setSearchParams] = useState<Partial<VideoListParam>>({});
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 加载视频列表
  const loadVideos = async (
    current = 1,
    size = 10,
    params?: Partial<VideoListParam>
  ) => {
    setTableLoading(true);
    try {
      const requestParams: VideoListParam = {
        current,
        size,
        ...searchParams,
        ...params,
      };
      const response = await AdminControllerService.videoListUsingPost(
        requestParams
      );
      if (response.data) {
        setVideos(response.data.records || []);
        setPagination({
          current: response.data.current || 1,
          pageSize: response.data.size || 10,
          total: response.data.total || 0,
        });
      }
    } catch (error: any) {
      console.error("加载视频列表失败:", error);
      message.error(error.response?.data?.message || "加载视频列表失败");
    } finally {
      setTableLoading(false);
    }
  };

  // 加载合集列表
  const loadCompilations = async () => {
    try {
      const response = await AdminControllerService.compilationListUsingPost();
      if (response.data) {
        setCompilations(response.data.records || []);
      }
    } catch (error: any) {
      console.error("加载合集列表失败:", error);
      message.error(error.response?.data?.message || "加载合集列表失败");
    }
  };

  useEffect(() => {
    loadVideos();
    loadCompilations();
  }, []);

  // 处理搜索
  const handleSearch = (values: any) => {
    const params: Partial<VideoListParam> = {
      title: values.title?.trim() || undefined,
      compilationId: values.compilationId || undefined,
    };

    // 处理日期范围
    if (values.dateRange && values.dateRange.length === 2) {
      params.createdTimeStart = values.dateRange[0].format(
        "YYYY-MM-DD HH:mm:ss"
      );
      params.createdTimeEnd =
        values.dateRange[1].format("YYYY-MM-DD") + " 23:59:59";
    }
    // 保存包含freeState的完整搜索参数用于前端状态管理
    const fullSearchParams = {
      ...params,
      freeState: values.freeState,
    };

    setSearchParams(fullSearchParams);
    setTimeout(() => {
      loadVideos(1, pagination.pageSize, fullSearchParams);
    }, 500);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setTimeout(() => {
      loadVideos(1, pagination.pageSize, {});
    }, 500);
  };
  const getFileUrl = async (fileName: string) => {
    const data = await Service.downloadImgUsingGet(fileName);
    console.log(data);
  };

  const columns: ColumnsType<VideoData> = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "封面",
      dataIndex: "coverId",
      key: "coverId",
      render: (coverId: string) =>
        coverId ? (
          <Space>
            <Image
              width={30}
              src={`/api/file/download/img?fileName=${coverId}&token=${getToken()}`}
            />
          </Space>
        ) : (
          <Tag color="default">未设置</Tag>
        ),
    },
    {
      title: "视频文件",
      dataIndex: "fileId",
      key: "fileId",
      render: (fileId: string) =>
        fileId ? (
          <Space>
            <Button
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                // 打开新窗口预览视频
                window.open(
                  `/api/file/download/video?fileName=${fileId}&token=${getToken()}`
                );
              }}
            >
              预览
            </Button>
          </Space>
        ) : (
          <Tag color="default">未设置</Tag>
        ),
    },
    {
      title: "合集",
      dataIndex: "compilationId",
      key: "compilationId",
      render: (compilationId: string) => {
        const compilation = compilations.find((c) => c.id === compilationId);
        return compilation ? compilation.name : compilationId || "未分配";
      },
    },
    {
      title: "排序",
      dataIndex: "sortNum",
      key: "sortNum",
      sorter: (a, b) => Number(a.sortNum || 0) - Number(b.sortNum || 0),
    },
    {
      title: "状态",
      key: "status",
      render: (_, record) => (
        <Space>
          {record.freeState && <Tag color="green">免费</Tag>}
          {!record.freeState && <Tag color="orange">付费</Tag>}
        </Space>
      ),
    },
    {
      title: "创建日期",
      dataIndex: "createdTime",
      key: "createdTime",
      render: (createdTime: string) => {
        if (!createdTime) return "-";
        return dayjs(createdTime).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>

          {record.freeState ? (
            <Popconfirm
              title="确定要取消置顶这个视频吗？"
              description="视频将不再置顶显示"
              onConfirm={() => handleCancelTop(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="default"
                size="small"
                icon={<VerticalAlignBottomOutlined />}
              >
                取消置顶
              </Button>
            </Popconfirm>
          ) : (
            <Popconfirm
              title="确定要免费置顶这个视频吗？"
              description="视频将被设置为免费并置顶显示"
              onConfirm={() => handleFreeTop(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="default"
                size="small"
                icon={<VerticalAlignTopOutlined />}
              >
                免费置顶
              </Button>
            </Popconfirm>
          )}

          <Popconfirm
            title="确定要删除这个视频吗？"
            onConfirm={() => record.id && handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingVideo(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (video: VideoData) => {
    setEditingVideo(video);
    form.setFieldsValue(video);
    setIsModalVisible(true);
    setVideoUploadSuccess(true);
    setUploadProgress(100);
  };

  const handleDelete = async (id: string) => {
    if (!id) {
      message.error("视频ID不能为空");
      return;
    }
    try {
      await AdminControllerService.deleteVideoUsingPost(id);
      message.success("删除成功");
      loadVideos(pagination.current, pagination.pageSize);
    } catch (error: any) {
      console.error("删除视频失败:", error);
      message.error(error.response?.data?.message || "删除失败");
    }
  };

  const handleFreeTop = async (video: VideoData) => {
    if (!video.id) {
      message.error("视频ID不能为空");
      return;
    }
    try {
      const videoData: VidVideo_ = {
        ...video,
        freeState: true,
      };
      await AdminControllerService.saveVideoUsingPost(videoData);
      message.success("免费置顶成功");
      loadVideos(pagination.current, pagination.pageSize);
    } catch (error: any) {
      console.error("免费置顶失败:", error);
      message.error(error.response?.data?.message || "免费置顶失败");
    }
  };

  const handleCancelTop = async (video: VideoData) => {
    if (!video.id) {
      message.error("视频ID不能为空");
      return;
    }
    try {
      const videoData: VidVideo_ = {
        ...video,
        freeState: false,
      };
      await AdminControllerService.saveVideoUsingPost(videoData);
      message.success("取消置顶成功");
      loadVideos(pagination.current, pagination.pageSize);
    } catch (error: any) {
      console.error("取消置顶失败:", error);
      message.error(error.response?.data?.message || "取消置顶失败");
    }
  };

  const handleModalOk = () => {
    form.validateFields().then(async (values) => {
      setLoading(true);
      try {
        const videoData: VidVideo_ = {
          ...values,
          sortNum: values.sortNum?.toString(),
        };

        if (editingVideo?.id) {
          // 编辑
          videoData.id = editingVideo.id;
        }
        // 视频是否上传成功
        if (!videoUploadSuccess) {
          message.error("请先上传视频");
          return;
        }

        await AdminControllerService.saveVideoUsingPost(videoData);
        message.success(editingVideo ? "修改成功" : "添加成功");
        setIsModalVisible(false);
        loadVideos(pagination.current, pagination.pageSize);
      } catch (error: any) {
        console.error("保存视频失败:", error);
        message.error(error.response?.data?.message || "保存失败");
      } finally {
        setLoading(false);
      }
    });
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setCoverUploading(false);
    setVideoUploading(false);
    setUploadProgress(0);
  };

  // 处理封面上传
  const handleCoverUpload: UploadProps["customRequest"] = async (options) => {
    const { file, onSuccess, onError } = options;
    setCoverUploading(true);
    try {
      const response = await Service.uploadFileUsingPost({
        file: file as Blob,
      });
      // 检查响应结构，可能是 response.data.fileName 或直接 response.fileName
      const fileName = response?.data?.fileFullName || response?.fileFullName;

      if (fileName) {
        form.setFieldsValue({ coverId: fileName });
        message.success("封面上传成功");
        onSuccess?.(response);
      } else {
        console.error("上传响应结构:", response);
        throw new Error("上传失败，未返回文件名");
      }
    } catch (error: any) {
      console.error("封面上传失败:", error);
      message.error(error.response?.data?.message || "封面上传失败");
      onError?.(error);
    } finally {
      setCoverUploading(false);
    }
  };
  // 视频上传成功
  const [videoUploadSuccess, setVideoUploadSuccess] = useState(false);
  // 上传进度
  // 处理视频上传
  const handleVideoUpload: UploadProps["customRequest"] = async (options) => {
    const { file, onSuccess, onError, onProgress } = options;
    setVideoUploadSuccess(false);
    setVideoUploading(true);
    setUploadProgress(1); // 立即显示1%进度，让用户知道上传已开始

    try {
      // 创建FormData用于文件上传
      const formData = new FormData();
      formData.append("file", file as Blob);

      // 使用XMLHttpRequest来支持进度监听
      const xhr = new XMLHttpRequest();

      // 监听上传进度
      xhr.upload.addEventListener("progress", (event) => {
        if (event.lengthComputable) {
          const percent = Math.round((event.loaded / event.total) * 100);
          console.log(`上传进度: ${percent}%`, {
            loaded: event.loaded,
            total: event.total,
          });
          setUploadProgress(percent);
          onProgress?.({ percent });
        }
      });

      // 设置请求完成回调
      xhr.onload = () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            console.log("视频上传响应:", response);
            // 检查响应结构，可能是 response.data.fileName 或直接 response.fileName
            const fileName =
              response?.data?.fileFullName || response?.fileFullName;
            if (fileName) {
              // 确保进度条显示100%
              setUploadProgress(100);
              form.setFieldsValue({ fileId: fileName });
              message.success("视频上传成功");
              setVideoUploadSuccess(true);
              onSuccess?.(response);
              // 延迟重置状态，让用户看到100%的进度
              setTimeout(() => {
                setVideoUploading(false);
                setUploadProgress(0);
              }, 1000);
            } else {
              console.error("上传响应结构:", response);
              throw new Error("上传失败，未返回文件名");
            }
          } catch (parseError) {
            console.error("解析响应失败:", parseError);
            message.error("上传失败，响应格式错误");
            onError?.(parseError as Error);
            setVideoUploading(false);
            setUploadProgress(0);
          }
        } else {
          const error = new Error(`上传失败，状态码: ${xhr.status}`);
          console.error("视频上传失败:", error);
          message.error("视频上传失败");
          onError?.(error as any);
          setVideoUploading(false);
          setUploadProgress(0);
        }
      };

      // 设置错误回调
      xhr.onerror = () => {
        const error = new Error("网络错误，上传失败");
        console.error("视频上传失败:", error);
        message.error("网络错误，视频上传失败");
        onError?.(error as any);
        setVideoUploading(false);
        setUploadProgress(0);
      };

      // 发送请求
      xhr.open("POST", "/api/file/upload");
      // 添加认证头
      const token = getToken();
      if (token) {
        xhr.setRequestHeader("Authorization", `Bearer ${token}`);
      }
      xhr.send(formData);
    } catch (error: any) {
      console.error("视频上传失败:", error);
      message.error(error.response?.data?.message || "视频上传失败");
      onError?.(error as any);
      setVideoUploading(false);
      setUploadProgress(0);
    }
  };

  return (
    <>
      {/* CSS动画样式 */}
      <style>
        {`
          @keyframes pulse {
            0% {
              opacity: 1;
              transform: scale(1);
            }
            50% {
              opacity: 0.7;
              transform: scale(1.1);
            }
            100% {
              opacity: 1;
              transform: scale(1);
            }
          }
        `}
      </style>

      <Card title="视频管理">
        {/* 搜索表单 */}
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="title" label="标题">
            <Input placeholder="请输入视频标题" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="compilationId" label="合集">
            <Select placeholder="请选择合集" style={{ width: 150 }} allowClear>
              {compilations.map((compilation) => (
                <Select.Option key={compilation.id} value={compilation.id}>
                  {compilation.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="freeState" label="是否免费">
            <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
              <Select.Option value={false}>否</Select.Option>
              <Select.Option value={true}>是</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="创建时间">
            <DatePicker.RangePicker
              placeholder={["开始日期", "结束日期"]}
              style={{ width: 240 }}
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加视频
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Table
          columns={columns}
          dataSource={videos}
          rowKey="id"
          loading={tableLoading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => loadVideos(page, size),
            onShowSizeChange: (current, size) => loadVideos(current, size),
          }}
        />

        <Modal
          title={editingVideo ? "编辑视频" : "添加视频"}
          open={isModalVisible}
          onOk={handleModalOk}
          onCancel={handleModalCancel}
          width={600}
          confirmLoading={loading}
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              freeState: false,
              sortNum: "1",
            }}
          >
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: "请输入视频标题" }]}
            >
              <Input placeholder="请输入视频标题" />
            </Form.Item>

            <Form.Item
              name="compilationId"
              label="合集"
              rules={[{ required: true, message: "请选择合集" }]}
            >
              <Select placeholder="请选择合集">
                {compilations.map((compilation) => (
                  <Select.Option key={compilation.id} value={compilation.id}>
                    {compilation.name}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="sortNum"
              label="排序"
              rules={[{ required: true, message: "请输入排序号" }]}
            >
              <Input type="number" placeholder="请输入排序号" />
            </Form.Item>

            <Form.Item name="coverId" label="封面">
              <div
                style={{
                  width: 240,
                  height: 140,
                  border: "2px dashed #e1e5e9",
                  borderRadius: 12,
                  position: "relative",
                  overflow: "hidden",
                  backgroundColor: "#ffffff",
                  transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
                  boxShadow: "0 2px 8px rgba(0, 0, 0, 0.06)",
                }}
              >
                {form.getFieldValue("coverId") ? (
                  <div
                    style={{
                      position: "relative",
                      width: "100%",
                      height: "100%",
                    }}
                  >
                    <Image
                      width={236}
                      height={136}
                      src={`/api/file/download/img?fileName=${form.getFieldValue(
                        "coverId"
                      )}&token=${getToken()}`}
                      fallback=""
                      style={{ objectFit: "cover", borderRadius: 10 }}
                      preview={{
                        mask: (
                          <div
                            style={{
                              color: "white",
                              fontSize: 14,
                              textAlign: "center",
                              fontWeight: 500,
                            }}
                          >
                            🔍 预览封面
                          </div>
                        ),
                      }}
                    />
                    <div
                      style={{
                        position: "absolute",
                        top: 8,
                        right: 8,
                        background: "rgba(0, 0, 0, 0.6)",
                        borderRadius: 20,
                        padding: "4px 8px",
                      }}
                    >
                      <Upload
                        customRequest={handleCoverUpload}
                        accept="image/jpeg,image/jpg,image/png"
                        showUploadList={false}
                        disabled={coverUploading}
                      >
                        <Button
                          size="small"
                          type="text"
                          icon={<UploadOutlined />}
                          loading={coverUploading}
                          style={{
                            fontSize: 12,
                            height: 28,
                            color: "white",
                            border: "none",
                            padding: "0 8px",
                          }}
                        >
                          更换
                        </Button>
                      </Upload>
                    </div>
                  </div>
                ) : (
                  <Upload
                    customRequest={handleCoverUpload}
                    accept="image/jpeg,image/jpg,image/png"
                    showUploadList={false}
                    disabled={coverUploading}
                  >
                    <div
                      style={{
                        width: "100%",
                        height: "100%",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                        justifyContent: "center",
                        cursor: "pointer",
                        transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
                        background:
                          "linear-gradient(135deg, #fafbfc 0%, #f4f6f8 100%)",
                        borderRadius: 10,
                        position: "relative",
                      }}
                      className="upload-area"
                      onMouseEnter={(e) => {
                        const container =
                          e.currentTarget.parentElement?.parentElement;
                        if (container) {
                          container.style.borderColor = "#1890ff";
                          container.style.backgroundColor = "#f8fcff";
                          container.style.boxShadow =
                            "0 4px 20px rgba(24, 144, 255, 0.12)";
                          container.style.transform = "translateY(-2px)";
                        }
                      }}
                      onMouseLeave={(e) => {
                        const container =
                          e.currentTarget.parentElement?.parentElement;
                        if (container) {
                          container.style.borderColor = "#e1e5e9";
                          container.style.backgroundColor = "#ffffff";
                          container.style.boxShadow =
                            "0 2px 8px rgba(0, 0, 0, 0.06)";
                          container.style.transform = "translateY(0)";
                        }
                      }}
                    >
                      <div
                        style={{
                          width: 56,
                          height: 56,
                          borderRadius: "16px",
                          backgroundColor: "#e6f7ff",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          marginBottom: 12,
                          border: "2px solid #bae7ff",
                          boxShadow: "0 2px 8px rgba(24, 144, 255, 0.1)",
                        }}
                      >
                        <UploadOutlined
                          style={{ fontSize: 24, color: "#1890ff" }}
                        />
                      </div>
                      <div
                        style={{
                          color: "#1890ff",
                          fontSize: 15,
                          fontWeight: 600,
                          marginBottom: 4,
                        }}
                      >
                        {coverUploading ? "📤 上传中..." : "📷 上传封面"}
                      </div>
                      <div
                        style={{
                          color: "#8c8c8c",
                          fontSize: 12,
                          textAlign: "center",
                          lineHeight: 1.4,
                        }}
                      >
                        支持 JPG、PNG 格式
                        <br />
                        <span style={{ color: "#bfbfbf" }}>建议尺寸 16:9</span>
                      </div>
                    </div>
                  </Upload>
                )}
              </div>
            </Form.Item>

            <Form.Item name="fileId" label="视频文件">
              <div
                style={{
                  width: 280,
                  height: 160,
                  border: "2px dashed #e1e5e9",
                  borderRadius: 12,
                  position: "relative",
                  overflow: "hidden",
                  backgroundColor: "#ffffff",
                  transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
                  boxShadow: "0 2px 8px rgba(0, 0, 0, 0.06)",
                }}
              >
                {form.getFieldValue("fileId") ? (
                  <div
                    style={{
                      position: "relative",
                      width: "100%",
                      height: "100%",
                    }}
                  >
                    <div
                      style={{
                        width: "100%",
                        height: "100%",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                        justifyContent: "center",
                        backgroundColor: "#f0f9ff",
                        border: "2px solid #52c41a",
                        borderRadius: 10,
                        background:
                          "linear-gradient(135deg, #f6ffed 0%, #f0f9ff 100%)",
                      }}
                    >
                      <div
                        style={{
                          width: 64,
                          height: 64,
                          borderRadius: "20px",
                          backgroundColor: "#f6ffed",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          marginBottom: 12,
                          border: "3px solid #b7eb8f",
                          boxShadow: "0 4px 12px rgba(82, 196, 26, 0.15)",
                        }}
                      >
                        <CheckCircleOutlined
                          style={{
                            fontSize: 28,
                            color: "#52c41a",
                          }}
                        />
                      </div>
                      <div
                        style={{
                          color: "#52c41a",
                          fontSize: 16,
                          fontWeight: 600,
                          marginBottom: 6,
                        }}
                      >
                        {videoUploadSuccess
                          ? "✅ 视频已上传"
                          : `上传中${uploadProgress}% ...`}
                      </div>
                      <div
                        style={{
                          color: "#666",
                          fontSize: 11,
                          backgroundColor: "rgba(255,255,255,0.8)",
                          padding: "4px 8px",
                          borderRadius: 12,
                          maxWidth: "200px",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {form.getFieldValue("fileId")}
                      </div>
                    </div>
                    <div
                      style={{
                        position: "absolute",
                        top: 8,
                        right: 8,
                        background: "rgba(0, 0, 0, 0.6)",
                        borderRadius: 20,
                        padding: "4px 8px",
                      }}
                    >
                      <Upload
                        customRequest={handleVideoUpload}
                        accept="video/mp4,video/avi,video/mov,video/wmv"
                        showUploadList={false}
                        disabled={videoUploading}
                      >
                        <Button
                          size="small"
                          type="text"
                          icon={<UploadOutlined />}
                          loading={videoUploading}
                          style={{
                            fontSize: 12,
                            height: 28,
                            color: "white",
                            border: "none",
                            padding: "0 8px",
                          }}
                        >
                          更换
                        </Button>
                      </Upload>
                    </div>
                  </div>
                ) : (
                  <Upload
                    customRequest={handleVideoUpload}
                    accept="video/mp4,video/avi,video/mov,video/wmv"
                    showUploadList={false}
                    disabled={videoUploading}
                  >
                    <div
                      style={{
                        width: "100%",
                        height: "100%",
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                        justifyContent: "center",
                        cursor: "pointer",
                        transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
                        background:
                          "linear-gradient(135deg, #fafbfc 0%, #f4f6f8 100%)",
                        borderRadius: 10,
                        position: "relative",
                      }}
                      onMouseEnter={(e) => {
                        const container =
                          e.currentTarget.parentElement?.parentElement;
                        if (container) {
                          container.style.borderColor = "#722ed1";
                          container.style.backgroundColor = "#f9f0ff";
                          container.style.boxShadow =
                            "0 4px 20px rgba(114, 46, 209, 0.15)";
                          container.style.transform = "translateY(-2px)";
                        }
                      }}
                      onMouseLeave={(e) => {
                        const container =
                          e.currentTarget.parentElement?.parentElement;
                        if (container) {
                          container.style.borderColor = "#e1e5e9";
                          container.style.backgroundColor = "#ffffff";
                          container.style.boxShadow =
                            "0 2px 8px rgba(0, 0, 0, 0.06)";
                          container.style.transform = "translateY(0)";
                        }
                      }}
                    >
                      <div
                        style={{
                          width: 64,
                          height: 64,
                          borderRadius: "20px",
                          backgroundColor: "#f0e6ff",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          marginBottom: 14,
                          border: "3px solid #d3adf7",
                          boxShadow: "0 4px 12px rgba(114, 46, 209, 0.12)",
                        }}
                      >
                        <UploadOutlined
                          style={{ fontSize: 28, color: "#722ed1" }}
                        />
                      </div>
                      <div
                        style={{
                          color: "#722ed1",
                          fontSize: 16,
                          fontWeight: 600,
                          marginBottom: 6,
                        }}
                      >
                        {videoUploading ? "📤 上传中..." : "🎬 上传视频"}
                      </div>
                      {videoUploading && (
                        <div
                          style={{
                            width: "100%",
                            marginBottom: 16,
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            background: "rgba(255, 255, 255, 0.95)",
                            backdropFilter: "blur(4px)",
                            display: "flex",
                            flexDirection: "column",
                            alignItems: "center",
                            justifyContent: "center",
                            borderRadius: 10,
                            zIndex: 10,
                          }}
                        >
                          <div
                            style={{
                              marginBottom: 16,
                              fontSize: 18,
                              color: "#722ed1",
                              textAlign: "center",
                              fontWeight: 700,
                              background:
                                "linear-gradient(135deg, #722ed1, #9254de)",
                              WebkitBackgroundClip: "text",
                              WebkitTextFillColor: "transparent",
                              backgroundClip: "text",
                            }}
                          >
                            📤 视频上传中...
                          </div>
                          <div
                            style={{
                              width: "80%",
                              marginBottom: 12,
                            }}
                          >
                            <div
                              style={{
                                marginBottom: 8,
                                fontSize: 24,
                                color: "#722ed1",
                                textAlign: "center",
                                fontWeight: 700,
                              }}
                            >
                              {uploadProgress}%
                            </div>
                            <Progress
                              percent={uploadProgress}
                              size="default"
                              strokeColor={{
                                "0%": "#722ed1",
                                "50%": "#9254de",
                                "100%": "#52c41a",
                              }}
                              showInfo={false}
                              strokeWidth={16}
                              trailColor="#f0f0f0"
                              style={{
                                filter:
                                  "drop-shadow(0 4px 8px rgba(114, 46, 209, 0.3))",
                              }}
                            />
                          </div>
                          <div
                            style={{
                              fontSize: 13,
                              color: "#666",
                              textAlign: "center",
                              fontWeight: 500,
                            }}
                          >
                            {uploadProgress < 100
                              ? "正在上传，请勿关闭页面..."
                              : "上传完成！"}
                          </div>
                        </div>
                      )}
                      <div
                        style={{
                          color: "#8c8c8c",
                          fontSize: 12,
                          textAlign: "center",
                          lineHeight: 1.4,
                        }}
                      >
                        {videoUploading ? (
                          <span style={{ color: "#722ed1" }}>
                            正在上传视频文件，请稍候...
                          </span>
                        ) : (
                          <>
                            支持 MP4、AVI、MOV 格式
                            <br />
                            <span style={{ color: "#bfbfbf" }}>
                              文件大小不超过 500MB
                            </span>
                          </>
                        )}
                      </div>
                    </div>
                  </Upload>
                )}
              </div>
            </Form.Item>

            <Form.Item name="freeState" label="是否免费">
              <Select>
                <Select.Option value={true}>是</Select.Option>
                <Select.Option value={false}>否</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </>
  );
};

export default VideoManagement;
